<template>
  <div :class="['tabs-head', layout, pageWidth]">
    <a-tabs
        type="editable-card"
        :class="[
      'tabs-container',
      layout,
      pageWidth,
      {
        affixed: affixed,
        'fixed-header': fixedHeader,
        collapsed: adminLayout.collapsed
      }
    ]"
        :active-key="active"
        :hide-add="true"
    >
        <a-tooltip placement="left" :title="lockTitle" slot="tabBarExtraContent">
          <a-icon
              theme="filled"
              @click="onLockClick"
              class="header-lock"
              :type="fixedTabs ? 'lock' : 'unlock'"
          />
        </a-tooltip>
      <a-tab-pane v-for="(page, index) in pageList" :key="page.path">
        <div
            slot="tab"
            class="tab"
            @contextmenu="e => onContextmenu(page.path, e)"
        >
          <a-icon
              @click="onRefresh(page)"
              :class="[
            'icon-sync',
            { hide: page.path !== active && !page.loading }
          ]"
              :type="page.loading ? 'loading' : 'sync'"
          />
          <div class="title" @click="onTabClick(page.path)" :ref="`title-${index}`">
            {{ pageName(page, index) }}
          </div>
          <a-icon
              @click="onClose(page.path)"
              class="icon-close"
              type="close"
          />
        </div>
      </a-tab-pane>
    </a-tabs>
    <div v-if="affixed" class="virtual-tabs"></div>
  </div>
</template>

<script>
import {mapState, mapMutations, mapActions, mapGetters} from "vuex";
import {getI18nKey} from "@/utils/routerUtil";

export default {
  name: "TabsHead",
  i18n: require("./i18n"),
  props: {
    pageList: Array,
    active: String,
    fixed: Boolean
  },
  watch: {
    pageList: {
      handler (newVal) {
        this.setPageTitle(newVal)
      }, deep: true},
    getLang: {
      handler() {
        this.setPageTitle(this.pageList)
      },
      deep: true,
      immediate: true // 立即执行一次
    }
  },
  data() {
    return {
      affixed: false,
      localPageList: this.pageList
    };
  },
  inject: ["adminLayout"],
  created() {
    this.affixed = this.fixedTabs;
  },
  mounted() {
    this.setPageTitle(this.localPageList)
  },
  computed: {
    ...mapState("setting", [
      "layout",
      "pageWidth",
      "fixedHeader",
      "fixedTabs",
      "customTitles"
    ]),
    ...mapGetters("setting", ['getLang']),
    lockTitle() {
      return this.$t(this.fixedTabs ? "unlock" : "lock");
    }
  },
  methods: {
    ...mapMutations("setting", ["setFixedTabs"]),
    ...mapActions(['updateCardMinHeight', 'updatePageTitleWidth']),
    onLockClick() {
      this.setFixedTabs(!this.fixedTabs);
      if (this.fixedTabs) {
        setTimeout(() => {
          this.affixed = true;
          this.updateCardMinHeight(835)
          this.$refreshPage(this.$route.path)
        }, 200);
      } else {
        this.affixed = false;
        this.updateCardMinHeight(770)
        this.$refreshPage(this.$route.path)
      }
    },
    onTabClick(key) {
      if (this.active !== key) {
        this.$emit("change", key);
      }
    },
    onClose(key) {
      this.$emit("close", key);
    },
    onRefresh(page) {
      this.$emit("refresh", page.path, page);
    },
    onContextmenu(pageKey, e) {
      this.$emit("contextmenu", pageKey, e);
    },
    pageName(page) {
      const pagePath = page.fullPath.split("?")[0];
      const custom = this.customTitles.find(item => item.path === pagePath);
      const title = (custom && custom.title) || page.title || this.$t(getI18nKey(page.keyPath))
      return (title);
    },
    setPageTitle(pageList) {
      let width = 0
      if (pageList.length>0) {
        pageList.forEach(el => {
          width += (54+this.calculateTextWidth(this.pageName(el)))
        })
      }
      this.updatePageTitleWidth(width+38)
      // this.$nextTick(() => {
      //   let width = 0
      //   if (pageList.length>0) {
      //     pageList.forEach((page, index) => {
      //       const titleRef = this.$refs[`title-${index}`][0]; // 获取单个元素
      //       if (titleRef) {
      //         width += (54+titleRef.offsetWidth)
      //       }
      //     });
      //   }
      //   console.log("pageList width:", width)
      //   this.updatePageTitleWidth(width+38)
      // })
    },
    calculateTextWidth(str) {
      let totalWidth = 0;
      for (let i = 0; i < str.length; i++) {
        const charCode = str.charCodeAt(i);
        // 判断是否为中文字符，包括繁体字
        if ((charCode >= 0x4E00 && charCode <= 0x9FA5) ||
            (charCode >= 0xF900 && charCode <= 0xFAFF)) {
          totalWidth += 14;
        }
        // 判断是否为大写字母或特定的长英文字符
        else if ((charCode >= 65 && charCode <= 90) || this.isLongEnglishChar(str[i])) {
          totalWidth += 10;
        }
        // 其他情况默认为短英文字符
        else {
          totalWidth += 7;
        }
      }
      return totalWidth;
    },
    isLongEnglishChar(char) {
      const longChars = 'wWmM';
      return longChars.includes(char);
    }
  }
};
</script>

<style scoped lang="less">
.tab {
  margin: 0 -16px;
  padding: 0 16px;
  font-size: 14px;
  user-select: none;
  transition: all 0.2s;
  .title {
    display: inline-block;
    height: 100%;
  }
  .icon-close {
    font-size: 12px;
    margin-left: 6px;
    margin-right: -4px !important;
    color: @text-color-second;
    &:hover {
      color: @text-color;
    }
  }
  .icon-sync {
    margin-left: -4px;
    color: @primary-4;
    transition: all 0.3s ease-in-out;
    &:hover {
      color: @primary-color;
    }
    font-size: 14px;
    &.hide {
      font-size: 0;
    }
  }
}
.tabs-head {
  margin: 0 auto;
  padding: 0 24px;
  &.head.fixed {
    width: 1400px;
  }
}
.tabs-container {
  margin: -16px auto 8px;
  transition: top, left 0.2s;
  .header-lock {
    font-size: 18px;
    cursor: pointer;
    color: @primary-3;
    &:hover {
      color: @primary-color;
    }
  }
  &.affixed {
    margin: 0 auto;
    top: 0px;
    padding: 8px 24px 0;
    position: fixed;
    height: 48px;
    z-index: 1;
    background-color: @layout-body-background;
    &.side,
    &.mix {
      right: 0;
      left: 256px;
      &.collapsed {
        left: 80px;
      }
    }
    &.head {
      width: inherit;
      padding: 8px 0 0;
      &.fluid {
        left: 0;
        right: 0;
        padding: 8px 24px 0;
        background: #fff;
      }
    }
    &.fixed-header {
      top: 64px;
    }
  }
}
.virtual-tabs {
  height: 48px;
}
</style>
